package com.candy.security.jwt.service;

import com.candy.common.exception.BaseException;
import com.candy.security.jwt.entity.LoginUser;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

@Service
public class AuthenticationService implements IAuthenticationService
{
	/**
	 * 获取用户账户
	 **/
	@Override
	public String getLoginName()
	{
		try
		{
			return getLoginUser().getLoginName();
		}
		catch (Exception e)
		{
			throw new BaseException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 获取用户
	 **/
	@Override
	public LoginUser getLoginUser()
	{
		try
		{
			Authentication authentication = SecurityContextHolder.getContext()
																 .getAuthentication();
			return (LoginUser) authentication.getPrincipal();
		}
		catch (Exception e)
		{
			throw new BaseException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
		}
	}

	/**
	 * 是否为管理员
	 *
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public boolean isAdmin(Long userId)
	{
		return userId != null && 1L == userId;
	}


	public static Collection<SimpleGrantedAuthority> getAuthorities(List<String> authoritieList)
	{
		Collection<SimpleGrantedAuthority> authoritieCollection = new HashSet<>();
		if(authoritieList!=null&&authoritieList.size()>0)
		{
			authoritieList.forEach(item->authoritieCollection.add(new SimpleGrantedAuthority(item)));
		}
		return authoritieCollection;
	}
}
